package gw.com.android.ui.system;

import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.gwtsz.gts2.hx.BuildConfig;
import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.PresenterImpl;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.utils.ColorThemeUtil;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.DeviceUtil;
import www.com.library.view.TintImageTextView;
import www.com.library.view.TintImageView;

/**
 * Created by reeta.zou on 2016/8/8.
 * 系统设置相关界面的适配器
 */
public class SystemSettingAdapter extends BaseExpandableListAdapter {
    private DataItemResult mGroupData = new DataItemResult();
    private ArrayList<DataItemResult> mResult = new ArrayList<DataItemResult>();
    private FragmentActivity mContext;
    private ConfigSettingDeal mSettingDeal;
    private boolean fromMe = false;
    private int unReadCount = 0;
    private PresenterImpl fragment;

    /**
     * @param groupData   组对象数据
     * @param result      子集合数据
     * @param settingDeal 相关的config处理对象
     */
    public SystemSettingAdapter(DataItemResult groupData, ArrayList<DataItemResult> result, FragmentActivity mContext, PresenterImpl fragment, ConfigSettingDeal settingDeal) {
        groupData.addItem(new DataItemDetail());    //  加这二行代码，是为了在list最底部加入一行分割线阿
        result.add(new DataItemResult());           //  加这二行代码，是为了在list最底部加入一行分割线阿
        this.mGroupData.appendItems(groupData);
        this.mResult.addAll(result);
        this.mContext = mContext;
        this.mSettingDeal = settingDeal;
        this.fragment = fragment;
    }

    @Override
    public int getGroupCount() {
        return mGroupData.getDataCount();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return mResult.get(groupPosition).getDataCount();
    }

    @Override
    public String getGroup(int groupPosition) {
        if (groupPosition >= 0 && groupPosition < getGroupCount()) {
//            Logger.e(mGroupData.getItem(groupPosition).getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
            return mGroupData.getItem(groupPosition).getString(ConfigType.CONFIG_TYPE_TITLE_TAG);
        }
        return "";
    }

    @Override
    public DataItemDetail getChild(int groupPosition, int childPosition) {
        DataItemResult result;
        if (groupPosition >= 0 && groupPosition < getGroupCount()) {
            result = mResult.get(groupPosition);
            if (childPosition >= 0 && childPosition < getChildrenCount(groupPosition)) {
                return result.getItem(childPosition);
            }
        }

        return null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = mContext.getLayoutInflater();
            GroupView vh = null;
            if (getGroupType(groupPosition) == 1) {
                convertView = inflater.inflate(R.layout.list_item_setting_logo, parent, false);
                vh = new GroupView(convertView);
            } else if (getGroupType(groupPosition) == 2) {
                convertView = inflater.inflate(R.layout.list_item_setting_group, parent, false);
                vh = new GroupView(convertView);
            } else {
                return null;
            }
            convertView.setTag(vh);
        }
        GroupView vh = (GroupView) convertView.getTag();
        String str = getGroup(groupPosition);
        if (getGroupType(groupPosition) == 1) {
            vh.mView.setText(AppMain.getAppString(R.string.about_version, BuildConfig.VERSION_NAME));
        } else if (getGroupType(groupPosition) == 2) {
            if (null != str) {
                vh.mView.setText(str);
            }
            if (groupPosition == 0) {
                vh.mView.setVisibility(View.GONE);
            } else {
                vh.mView.setVisibility(View.VISIBLE);
            }
        }
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        int childType = getChildType(groupPosition, childPosition);
        if (convertView == null) {
            LayoutInflater inflater = mContext.getLayoutInflater();
            if (childType == CONFIG_TYPE_TYPE_CENTER) {
                convertView = inflater.inflate(R.layout.list_item_setting_center, parent, false);
                ItemCenterView vh = new ItemCenterView(convertView);
                convertView.setTag(vh);
            } else if (childType == CONFIG_TYPE_TYPE_SWITCH) {
                convertView = inflater.inflate(R.layout.list_item_setting_switch, parent, false);
                ItemSwitchView vh = new ItemSwitchView(convertView);
                convertView.setTag(vh);
            } else if (childType == CONFIG_TYPE_TYPE_CHECK) {
                convertView = inflater.inflate(R.layout.list_item_setting_check, parent, false);
                ItemCheckView vh = new ItemCheckView(convertView);
                convertView.setTag(vh);
            } else if (childType == CONFIG_TYPE_TYPE_CUSTOM) {
                convertView = inflater.inflate(R.layout.list_item_setting_custom, parent, false);
                ItemCustomView vh = new ItemCustomView(convertView);
                convertView.setTag(vh);
            } else if (childType == CONFIG_TYPE_TYPE_FORM_ME) {
                convertView = inflater.inflate(R.layout.list_item_icon_arrow, parent, false);
                ItemIconArrowView vh = new ItemIconArrowView(convertView);
                convertView.setTag(vh);
            } else {
                convertView = inflater.inflate(R.layout.list_item_setting_arraw, parent, false);
                ItemArrawView vh = new ItemArrawView(convertView);
                convertView.setTag(vh);
            }
        }
        final DataItemDetail item = getChild(groupPosition, childPosition);
        if (null != item) {
            if (childType == CONFIG_TYPE_TYPE_CENTER) {
                ItemCenterView vh = (ItemCenterView) convertView.getTag();
                vh.mView.setText(item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
                String key = item.getString(ConfigType.CONFIG_TYPE_KEY_TAG);
                if (key.equals(ConfigType.EXIT_TAG)) {
                    vh.mView.setTextColor(mContext.getResources().getColor(R.color.color_k));
                } else {
                    vh.mView.setTextColor(mContext.getResources().getColor(R.color.color_k));
                }
            } else if (childType == CONFIG_TYPE_TYPE_SWITCH) {
                //开关
                ItemSwitchView vh = (ItemSwitchView) convertView.getTag();
                String subTitle = item.getString(ConfigType.CONFIG_TYPE_SUB_DES_TAG);
                if (TextUtils.isEmpty(subTitle)) {
                    vh.container.setVisibility(View.GONE);
                    vh.mView.setText(item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
                } else {
                    vh.container.setVisibility(View.VISIBLE);
                    vh.title.setText(item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
                    vh.subTitle.setText(subTitle);
                }
                vh.divider.setVisibility(isLastChild ? View.GONE : View.VISIBLE);
                vh.mSwitchView.setChecked(item.getBoolean("isCheck"));
                vh.mSwitchView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            //开启
                            Logger.e("开启开启开启" + item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
                            mSettingDeal.onViewClickSwitch(mContext, item, true);
                        } else {
                            //关闭
                            Logger.e("关闭关闭关闭" + item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
                            mSettingDeal.onViewClickSwitch(mContext, item, false);
                        }
                    }
                });
                //check项
            } else if (childType == CONFIG_TYPE_TYPE_CHECK) {
                ItemCheckView vh = (ItemCheckView) convertView.getTag();
                String value = item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG);
                vh.mView.setText(value);
                vh.divider.setVisibility(isLastChild ? View.GONE : View.VISIBLE);
                setCheckView(item.getString(ConfigType.CONFIG_TYPE_KEY_TAG), value, vh.mCheckView);
            } else if (childType == CONFIG_TYPE_TYPE_CUSTOM) {
                ItemCustomView vh = (ItemCustomView) convertView.getTag();
                vh.mView.setText(item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
                //vh.mValueView.setMovementMethod(LinkMovementMethod.getInstance());
                vh.mValueView.setText(vh.getClickableSpan(item));
                if (ConfigType.PHONE_TAG.equals(item.getString(ConfigType.CONFIG_TYPE_KEY_TAG))) {
                    vh.mValueView.setTextColor(ColorThemeUtil.instance().color_k);
                } else if (ConfigType.CLOSE_ORDER_NUMBER_TAG.equals(item.getString(ConfigType.CONFIG_TYPE_KEY_TAG))) {
                    vh.mValueView.setTextColor(ColorThemeUtil.instance().color_k);
                    vh.mSubView.setVisibility(View.VISIBLE);
                    vh.mSubView.setText(R.string.close_order_number_descript);
                }
                vh.divider.setVisibility(isLastChild ? View.GONE : View.VISIBLE);
                //vh.mValueView.setHighlightColor(ColorThemeUtil.instance().color_c);
                vh.mValueView.setTag(item);
            } else if (childType == CONFIG_TYPE_TYPE_FORM_ME) {
                ItemIconArrowView vh = (ItemIconArrowView) convertView.getTag();
                vh.mContent.setText(item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
                vh.redPoint.setVisibility(View.INVISIBLE);
                vh.redCount.setVisibility(View.INVISIBLE);
                vh.subTitle.setVisibility(View.INVISIBLE);
                String key = item.getString(ConfigType.CONFIG_TYPE_KEY_TAG);
                if (key.equals(ConfigType.BULLENTIN_TYPE_TAG)) {
                    int count = unReadCount;
                    if (count > 0) {
                        vh.redCount.setVisibility(View.VISIBLE);
                        if (count > 99) {
                            vh.redCount.setText("99+");
                        } else {
                            vh.redCount.setText(String.valueOf(count));
                        }
                    } else {
                        vh.redCount.setVisibility(View.GONE);
                    }
                }
                if (key.equals(ConfigType.SWITCH_REAL_TAG)) {
                    vh.subTitle.setVisibility(View.VISIBLE);
                    vh.subTitle.setText(R.string.me_switch_real_subtitle);
                    vh.subTitle.setTextColor(0xFFA6A6A6);
                    Drawable drawable = mContext.getResources().getDrawable(R.mipmap.a_me_hot);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    vh.mContent.setCompoundDrawablePadding(DeviceUtil.instance().dip2px(2, mContext));
                    vh.mContent.setCompoundDrawables(drawable, null, null, null);
                    vh.mContent.setPadding(DeviceUtil.instance().dip2px(10, mContext), 0, 0, 0);
                } else if (key.equals(ConfigType.RECOMMENDED_TAG)) {
                    vh.subTitle.setVisibility(View.VISIBLE);
                    vh.subTitle.setText(R.string.me_invite_desc);
                    vh.subTitle.setTextColor(0xFFFC9A4B);
                } else {
                    vh.subTitle.setVisibility(View.GONE);
                }
                if (key.equals("newNotice")) {
                    if (!GTConfig.instance().isNewNoticeClicked()) {
                        vh.redPoint.setVisibility(View.VISIBLE);
                    }
                } else if (key.equals(ConfigType.SYSTEM_SETTING_TAG)) {
                    if (GTConfig.instance().hasNewVersion) {
                        vh.redPoint.setVisibility(View.VISIBLE);
                    } else {
                        vh.redPoint.setVisibility(View.GONE);
                    }
                }
                vh.divider.setVisibility(getChildrenCount(groupPosition) == childPosition + 1 ? View.INVISIBLE : View.VISIBLE);
            } else {
                //带选择和箭头的
                ItemArrawView vh = (ItemArrawView) convertView.getTag();
                vh.mView.setText(item.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
                vh.mArraw.setText(item.getString(ConfigType.CONFIG_TYPE_VALUE_TAG));
                if (item.getString(ConfigType.CONFIG_TYPE_KEY_TAG).equals(ConfigType.VERSION_UPDATE_TAG)) {
                    if (GTConfig.instance().hasNewVersion) {
                        vh.mNewView.setVisibility(View.VISIBLE);
                    } else {
                        vh.mNewView.setVisibility(View.GONE);
                    }
                } else {
                    vh.mNewView.setVisibility(View.GONE);
                }
                vh.divider.setVisibility(isLastChild ? View.GONE : View.VISIBLE);
            }
        }
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    @Override
    public int getGroupType(int groupPosition) {
        String title = getGroup(groupPosition);
        if (title.equals(ConfigType.CONFIG_TYPE_TYPE_LOGO_TAG)) {
            return 1;
        } else {
            return 2;
        }
    }

    @Override
    public int getGroupTypeCount() {
        return 3;
    }

    // childType常量定义
    private final int CONFIG_TYPE_TYPE_FORM_ME = 0;
    private final int CONFIG_TYPE_TYPE_CENTER = 1;//中间显示文字
    private final int CONFIG_TYPE_TYPE_SWITCH = 2;//开关形式
    private final int CONFIG_TYPE_TYPE_CHECK = 3;//check类型
    private final int CONFIG_TYPE_TYPE_CUSTOM = 4;//自定义
    private final int CONFIG_TYPE_TYPE_TEXT_ARROW = 5;//带箭头，箭头文字

    @Override
    public int getChildType(int groupPosition, int childPosition) {
        if (fromMe) {
            return CONFIG_TYPE_TYPE_FORM_ME;
        }
        DataItemDetail item = getChild(groupPosition, childPosition);
        String type = item.getString(ConfigType.CONFIG_TYPE_TYPE_TAG);

        if (type.equals(ConfigType.CONFIG_TYPE_TYPE_CENTER_TAG)) {
            return CONFIG_TYPE_TYPE_CENTER;

        } else if (type.equals(ConfigType.CONFIG_TYPE_TYPE_SWITCH_TAG)) {
            return CONFIG_TYPE_TYPE_SWITCH;

        } else if (type.equals(ConfigType.CONFIG_TYPE_TYPE_CHECK_TAG)) {
            return CONFIG_TYPE_TYPE_CHECK;

        } else if (type.equals(ConfigType.CONFIG_TYPE_TYPE_CUSTOM_TAG)) {
            return CONFIG_TYPE_TYPE_CUSTOM;

        } else {
            return CONFIG_TYPE_TYPE_TEXT_ARROW;

        }
    }

    @Override
    public int getChildTypeCount() {
        return 6;
    }

    class GroupView {
        @BindView(R.id.item_title)
        TextView mView;

        public GroupView(View itemView) {
            ButterKnife.bind(this, itemView);
        }
    }

    class ItemCenterView {
        @BindView(R.id.item_title)
        TextView mView;

        public ItemCenterView(View itemView) {
            ButterKnife.bind(this, itemView);
        }
    }

    class ItemCheckView {
        @BindView(R.id.item_title)
        TextView mView;
        @BindView(R.id.item_value)
        TintImageView mCheckView;
        @BindView(R.id.view_divider)
        View divider;

        public ItemCheckView(View itemView) {
            ButterKnife.bind(this, itemView);
        }
    }

    class ItemArrawView {
        @BindView(R.id.item_title)
        TextView mView;
        @BindView(R.id.new_tips)
        ImageView mNewView;
        @BindView(R.id.item_value)
        TintImageTextView mArraw;
        @BindView(R.id.view_divider)
        View divider;

        public ItemArrawView(View itemView) {
            ButterKnife.bind(this, itemView);
        }
    }

    class ItemSwitchView {
        @BindView(R.id.item_title)
        TextView mView;
        @BindView(R.id.item_value)
        CheckBox mSwitchView;
        @BindView(R.id.item_title_container)
        ViewGroup container;
        @BindView(R.id.item_title_main)
        TextView title;
        @BindView(R.id.item_title_sub)
        TextView subTitle;
        @BindView(R.id.view_divider)
        View divider;

        public ItemSwitchView(View itemView) {
            ButterKnife.bind(this, itemView);
        }
    }

    class ItemIconArrowView {
        @BindView(R.id.item_title)
        TextView mContent;
        @BindView(R.id.item_redpoint)
        View redPoint;
        @BindView(R.id.item_redcount)
        TextView redCount;
        @BindView(R.id.item_subtitle)
        TextView subTitle;
        @BindView(R.id.item_divider)
        View divider;

        ItemIconArrowView(View itemView) {
            ButterKnife.bind(this, itemView);
        }
    }

    class ItemCustomView {
        @BindView(R.id.item_title)
        TextView mView;
        @BindView(R.id.item_subtitle)
        TextView mSubView;
        @BindView(R.id.item_value)
        TextView mValueView;
        @BindView(R.id.view_divider)
        View divider;

        public ItemCustomView(View itemView) {
            ButterKnife.bind(this, itemView);
        }

        /**
         * 根据文字内容设置点击事件
         *
         * @param item
         * @return
         */
        private CharSequence getClickableSpan(final DataItemDetail item) {
            String value = item.getString(ConfigType.CONFIG_TYPE_VALUE_TAG);
            value = ConfigUtil.instance().mConfigObject.optString(value);
            String[] values = null;
            if (value.contains(",")) {
                values = value.split(",");
                value = value.replace(",", "\n");
            } else {
                values = new String[1];
                values[0] = value;
            }
            return value;
        }
    }

    /**
     * Check类型设置各项值
     *
     * @param key
     * @return
     */
    private void setCheckView(String key, String value, TintImageView mCheckView) {
        if (key.equals(ConfigType.ZH_CN_TAG)) {
            if (GTConfig.instance().getLanguage().equals(GTConfig.LANG_ZH_CN)) {
                mCheckView.setImageResource(R.mipmap.a_smalledit_check);
            } else {
                mCheckView.setImageResource(R.mipmap.a_smalledit_uncheck);
            }
        } else if (key.equals(ConfigType.ZH_TW_TAG)) {
            if (GTConfig.instance().getLanguage().equals(GTConfig.LANG_ZH_TW)) {
                mCheckView.setImageResource(R.mipmap.a_smalledit_check);
            } else {
                mCheckView.setImageResource(R.mipmap.a_smalledit_uncheck);
            }
        } else if (key.equals(ConfigType.GREEN_UP_TAG)) {
            if (GTConfig.instance().getPrefColorConfig().equals(GTConfig.COLOR_GREEN_RISE)) {
                mCheckView.setImageResource(R.mipmap.a_smalledit_check);
            } else {
                mCheckView.setImageResource(R.mipmap.a_smalledit_uncheck);
            }
        } else if (key.equals(ConfigType.RED_UP_TAG)) {
            if (GTConfig.instance().getPrefColorConfig().equals(GTConfig.COLOR_RED_RISE)) {
                mCheckView.setImageResource(R.mipmap.a_smalledit_check);
            } else {
                mCheckView.setImageResource(R.mipmap.a_smalledit_uncheck);
            }
        } else {
            if (key.equals(AppTerminal.instance().getZoneType() + "")) {
                mCheckView.setImageResource(R.mipmap.a_smalledit_check);
            } else {
                mCheckView.setImageResource(R.mipmap.a_smalledit_uncheck);
            }
        }
    }

    public void setFromMe(boolean fromMe) {
        this.fromMe = fromMe;
    }

    public void setUnReadCount(int unReadCount) {
        this.unReadCount = unReadCount;
    }

    /**
     * 设置绑定的listview和点击事件
     *
     * @param listView
     */
    public void setListView(ExpandableListView listView, final String title) {
        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                DataItemDetail mItem = getChild(groupPosition, childPosition);
                if (null == mItem) {
                    return true;
                }
                mSettingDeal.onViewClick(mContext, fragment, mItem, title, SystemSettingAdapter.this);
                if (mItem.getString(ConfigType.CONFIG_TYPE_TYPE_TAG).equals(ConfigType.CONFIG_TYPE_TYPE_CHECK_TAG)) {
                    notifyDataSetChanged();
                }
                String key = mItem.getString(ConfigType.CONFIG_TYPE_KEY_TAG);
                if ("newNotice".equals(key)) {
                    GTConfig.instance().setNewNoticeClicked(true);
                    notifyDataSetChanged();
                }
                return false;
            }
        });
    }
}